package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.TravelComment;
import cn.wolfcode.luowowo.query.TravelCommentQuery;
import cn.wolfcode.luowowo.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 游记评论实现
 */
@Service
//@Transactional mongodb事务必须复制集方式
public class TravelCommentServiceImpl implements ITravelCommentService {

    //spring-data-mongodb中的查询方式有两种repository(不能分页操作)和template
    //Spring-boot集成redis持久化数据库
    @Autowired
    private TravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(TravelComment travelComment) {

        travelComment.setId(null);
        travelComment.setCreateTime(new Date());

        // 维护关联的评论
        String refId = travelComment.getRefComment().getId();
        if(StringUtils.hasLength(refId)){
            // 回复评论
            TravelComment refcomment = this.get(refId);
            travelComment.setRefComment(refcomment);
            travelComment.setType(TravelComment.TRAVLE_COMMENT_TYPE_COMMENT);
        }
        repository.save(travelComment);
    }

    @Override
    public void delete(String id) {

        repository.deleteById(id);
    }

    @Override
    public void update(TravelComment travelComment) {

        repository.save(travelComment);
    }

    @Override
    public TravelComment get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<TravelComment> listAll() {
        return repository.findAll();
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {

        Query query = new Query();

        if(StringUtils.hasLength(qo.getTravelId())){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));

        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,
                qo.getPageSize(), Sort.Direction.DESC,"createTime");

        return DBHelper.query(template,TravelComment.class,query,pageable);
    }

    // 查询所有游记评论的集合
    @Override
    public List<TravelComment> queryByTravelId(String travelId) {

        return repository.findByTravelId(travelId);
    }
}
